package scrum.client.common;

import java.util.ArrayList;
import java.util.List;

import scrum.client.Dao;
import scrum.client.admin.User;
import scrum.client.project.Project;
import scrum.client.project.ProjectGroup;
import scrum.client.project.Requirement;

public class RequirementsFilter_ByProjectGroup_Multiple extends RequirementsFilter {

	protected List<ProjectGroup> groups;

	public RequirementsFilter_ByProjectGroup_Multiple() {
		groups = new ArrayList<ProjectGroup>();
	}

	public RequirementsFilter_ByProjectGroup_Multiple(User user, Project project) {
		groups = findGroups(user, project);
	}

	public void setup(User user, Project project) {
		groups = findGroups(user, project);
	}

	/**
	 * @param user
	 * @param project
	 * @return the ProjectGroups linked to the 'user' in the 'Project'
	 */
	protected List<ProjectGroup> findGroups(User user, Project project) {
		List<ProjectGroup> pGroups = Dao.get().getProjectGroupsByGroupMember(user);
		List<ProjectGroup> userGroups = new ArrayList<ProjectGroup>();

		for (int i = 0; i < pGroups.size(); i++) {
			if (pGroups.get(i).isProject(project)) {
				userGroups.add(pGroups.get(i));
			}
		}
		return userGroups;
	}

	@Override
	protected List<Requirement> doFilter(List<Requirement> toFilter) {
		ArrayList<Requirement> toRetain = new ArrayList<Requirement>();
		for (ProjectGroup g : groups) {
			toRetain.addAll(g.getStoriesAssociates());
		}

		if (!toRetain.isEmpty()) // don't try it if not needed
			toFilter.retainAll(toRetain);
		else toFilter = new ArrayList<Requirement>();

		return toFilter;
	}

	@Override
	protected boolean setupDone() {
		return !groups.isEmpty();
	}

}
